<template>
  <div class="new-article">
    <h2>{{ articleId ? '编辑文章' : '新建文章' }}</h2>

    <el-input v-model="title" placeholder="请输入文章标题" class="title-input" />

    <v-md-editor v-model="content" height="500px" />

    <!-- 标签多选，标签来自接口 -->
    <el-select
      v-model="selectedTagIds"
      multiple
      placeholder="请选择标签"
      class="tag-select"
      style="margin: 16px 0;"
      :collapse-tags="true"
    >
      <el-option
        v-for="tag in tagsList"
        :key="tag.id"
        :label="tag.name"
        :value="tag.id"
      />
    </el-select>

    <div>
      <el-button type="primary" class="submit-btn" @click="submitArticle">
        发布文章
      </el-button>

      <el-button class="cancel-btn" @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import VMdEditor from '@kangc/v-md-editor'
import VuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js'
import '@kangc/v-md-editor/lib/style/base-editor.css'
import '@kangc/v-md-editor/lib/theme/style/vuepress.css'
import Prism from 'prismjs'

import { getAllTags } from '@/api/tag'
import * as articleApi from '@/api/article'
import { useUserStore } from '@/stores/user'

VMdEditor.use(VuepressTheme, { Prism })

const props = defineProps<{
  articleId: number | null
}>()

const emit = defineEmits(['cancel', 'saved'])

const title = ref('')
const content = ref('')
const selectedTagIds = ref<number[]>([])
const tagsList = ref<{ id: number; name: string }[]>([])

const userStore = useUserStore()

async function loadTags() {
  try {
    const res = await getAllTags()
    if (res.code === 0 && Array.isArray(res.data)) {
      tagsList.value = res.data
    } else {
      console.warn('获取标签失败:', res.message)
    }
  } catch (error) {
    console.error('请求标签接口出错', error)
  }
}

async function loadArticleDetail(id: number) {
  try {
    const res = await articleApi.getArticleDetail(id)
    if (res.code === 0 && res.data) {
      title.value = res.data.title
      content.value = res.data.content

      // 从返回的 tags 中提取标签 ID
      selectedTagIds.value = Array.isArray(res.data.tags)
        ? res.data.tags.map(tag => tag.id)
        : []

    } else {
      alert(res.message || '获取文章详情失败')
    }
  } catch (error) {
    console.error(error)
    alert('请求文章详情接口失败')
  }
}

onMounted(() => {
  loadTags()
  if (props.articleId) {
    loadArticleDetail(props.articleId)
  }
})

watch(() => props.articleId, (newId) => {
  if (newId) {
    loadArticleDetail(newId)
  } else {
    title.value = ''
    content.value = ''
    selectedTagIds.value = []
  }
})

function submitArticle() {
  if (!title.value.trim()) {
    alert('请输入标题')
    return
  }
  if (!content.value.trim()) {
    alert('请输入内容')
    return
  }
  if (selectedTagIds.value.length === 0) {
    alert('请选择至少一个标签')
    return
  }
  if (!userStore.userInfo || !userStore.userInfo.id) {
    alert('请先登录')
    return
  }

  if (props.articleId) {
    emit('saved', {
      id: props.articleId,
      title: title.value,
      content: content.value,
      tag_ids: selectedTagIds.value,
    })
  } else {
    emit('saved', {
      title: title.value,
      content: content.value,
      tag_ids: selectedTagIds.value,
      author_id: userStore.userInfo.id,
    })
  }
}

function cancel() {
  emit('cancel')
}
</script>

<style scoped>
.new-article {
  max-width: 960px;
  margin: 0 auto;
  padding: 24px;
}

.title-input {
  margin-bottom: 16px;
}

.submit-btn {
  margin-top: 16px;
  margin-right: 10px;
}

.cancel-btn {
  margin-top: 16px;
}

.tag-select {
  width: 300px;
}
</style>
